<template>
  <div>
    <!-- 新增角色的弹框 -->
    <el-dialog title="新增角色" :visible="showDialog" @close="closeFn">
      <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="角色名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row>
          <el-button type="primary" size="small" @click="submit">确定</el-button>
          <el-button size="small" @click="closeFn">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addRoles, getRoleDetailById, editRole } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入角色名称', tigger: 'blur' },
          {
            min: 2,
            max: 6,
            message: '角色名称的长度在2到6个字符',
            tigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入角色描述', tigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '角色描述的长度在1到300字之间',
            tigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 获取角色详情
    async getRoleDetail(id) {
      const res = await getRoleDetailById(id)
      this.formData = res.data
    },
    // 新增提交按钮
    async submit() {
      // 校验表单
      await this.$refs.form.validateField()
      // 发送请求
      // 判断是否有id，有则是进行编辑
      if (this.formData.id) {
        // 编辑
        await editRole(this.formData)
      } else {
        // 新增
        await addRoles(this.formData)
      }
      // 更新列表
      this.$emit('update')
      // 关闭弹窗
      this.closeFn()
    },
    // 关闭弹窗
    closeFn() {
      // 关闭弹窗
      this.$emit('update:showDialog', false)
      // 清空表单数据
      this.formData = { title: '', description: '' }
      // 清空表单校验
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>
</style>
